<template>
  <div class="home">
    <input type="text" placeholder="Search..." v-model="val" @keyup.enter="search">
    <p>
      <input type="checkbox" name="stock" id="stock" :checked="checked" @click="stocked">
      Only show products in stock
    </p>
    <div class="home-list">
      <h5>
        <span>Name</span><span>Price</span>
      </h5>
      <div v-for="(item,index) in list" :key="index">
        <h4 v-show="item.category!==''">{{item.category}}</h4>
        <ul>
          <li>
            <span :class="item.stocked?'':'unstock'">{{item.name}}</span><span>{{item.price}}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  components: {
  },
  data() {
    return {
      products: [
        {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
        {category: "", price: "$9.99", stocked: true, name: "Baseball"},
        {category: "", price: "$29.99", stocked: false, name: "Basketball"},
        {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
        {category: "", price: "$399.99", stocked: false, name: "iPhone 5"},
        {category: "", price: "$199.99", stocked: true, name: "Nexus 7"}
      ],
      list: [],
      checked: false,
      val: ''
    }
  },
  methods: {
    search() { //搜索
      if (this.val=='') {
        this.list = this.products
      }else {
        this.list = this.list.filter(item=>{
          if (item.name.indexOf(this.val)!==-1||item.price.indexOf(this.val)!==-1) {
            console.log(item)
            return item
          }
        })
      }
    },
    stocked() { //切换有库存或全部
      if (this.checked == false) {
        this.checked = true
        this.list = this.products.filter(item=>{
          return item.stocked == true
        })
      } else {
        this.checked = false
        this.list = this.products
      }
    }
  },
  mounted() {
    this.list = this.products
  },
}
</script>
<style lang="scss">
  .home {
    width: 400px;
    margin: 10px;
    >p {
      margin-top: 10px;
    }
  }
  .home-list {
    width: 200px;
    text-align: center;
    margin-top: 20px;
    span {
      display: inline-block;
      width: 50%;
      text-align: left;
    }
    h4 {
      margin: 5px 0;
    }
    ul {
      list-style: none;
    }
  }
  .unstock {
    color: #ff6600;
  }
</style>